package org.xukai.common.util;

import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author xukai
 * @desc
 * @date 2016-09-11-下午 1:47
 */
public class PlaceHolderUtils {

    private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("[$][{][^{}]+[}]");
    private static final Pattern PLACEHOLDER_VALUEKEY_PATTERN = Pattern.compile("[^${}]+");

    public PlaceHolderUtils() {
    }

    public static void main(String[] args) {
        String s = "昵称是处女$(x小傻子}啊是小处男${233}{ads}sa";
        Matcher matcher = PLACEHOLDER_VALUEKEY_PATTERN.matcher(s);
        while(matcher.find()){
            System.out.println(matcher.group());

        }
    }
    public static void convertProperties(Properties properties) {
        Iterator var2 = properties.entrySet().iterator();

        while(var2.hasNext()) {
            Map.Entry entry = (Map.Entry)var2.next();
            String key = (String)entry.getKey();
            String value = (String)entry.getValue();
            value = resolveValue(value, properties);
            properties.put(key, value);
        }

    }

    public static String resolveValue(String value, Properties properties) {
        Matcher matcherOne = PLACEHOLDER_PATTERN.matcher(value);

        while(matcherOne.find()) {
            String matcherTwo = matcherOne.group();
            Matcher valueKeyMatcher = PLACEHOLDER_VALUEKEY_PATTERN.matcher(matcherTwo);
            if(valueKeyMatcher.find()) {
                String valueKey = valueKeyMatcher.group();
                value = value.replace(matcherTwo, (String)properties.get(valueKey));
            }
        }

        Matcher matcherTwo1 = PLACEHOLDER_PATTERN.matcher(value);
        if(matcherTwo1.find()) {
            value = resolveValue(value, properties);
        }

        return value;
    }
}
